/*
 * @Author: 罗云海
 * @Date: 2021-01-26 15:31:38
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-02-26 14:46:00
 * @Description: 地址选择插件
 */
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  Modal,
  TouchableOpacity,
  FlatList,
} from 'react-native';
import {
  splitLineColor_lightgray,
  fontColorBlack,
  mainBgColorWhite,
  fontColorCoffee,
  px2dp
} from '@/styles';
import adressApi from '@/api/address';
import { msg } from '../common';

export default class Adress extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      act: 0,
      code: '',
      label: this.handelLevel(),
      adressList: [],
    };
  }

  componentDidMount() {
    this.getAdressList(this.state.code);
  }

  // 处理级数
  handelLevel=() => {
    const { level } = this.props;
    let label = [
      { name: '省份', type: 'province', code: '', selectName: '' },
      { name: '城市', type: 'city', code: '', selectName: '' },
      { name: '县区', type: 'county', code: '', selectName: '' },
    ];
    label = label.slice(0, level);
    return label;
  }

  getAdressList = (code) => {
    return new Promise((resolve, reject) => {
      adressApi.getAddressListNew({ parentCode: code }).then((res) => {
        // console.log(res);
        this.setState({ adressList: res }, () => {
          if (this._getRef) {
            this._getRef.scrollToOffset({ offset: 0 });
          }
        });

        resolve(res); // 数据处理完成
      });
    });
  };

  setModalVisible = (visible) => {
    this.setState({ modalVisible: visible });
  };

  checkDetail() {
    this.props.checkDetail && this.props.checkDetail();
  }

  changeVisible = () => {
    this.reset();
    this.props.changeVisible && this.props.changeVisible();
  };

  getAdressData = () => {
    this.props.getAdressData && this.props.getAdressData();
  };

  render() {
    const { visible } = this.props;
    const { adressList, label, act } = this.state;
    return (
      <Modal
        animationType='slide'
        transparent
        visible={visible}
        onRequestClose={() => this.changeVisible()}
      >
        <TouchableOpacity
          style={styles.centeredView}
          onPress={() => this.changeVisible()}
        />
        <View style={styles.adressWrap}>
          <View style={styles.label}>
            <View style={styles.labelItem}>
              {label &&
                  label.map((v, i) => {
                    return (
                      <TouchableOpacity activeOpacit={1} onPress={() => this.handleLabel(v, i)} key={i}>
                        <Text
                          style={[
                            act == i ? styles.actLable : '',
                            styles.itemName,
                          ]}
                          key={i}
                        >
                          {v.name}
                        </Text>
                      </TouchableOpacity>
                    );
                  })}
            </View>
            <TouchableOpacity onPress={() => this.submit()}>
              <Text style={styles.submitText}>确定</Text>
            </TouchableOpacity>
          </View>
          <FlatList
            ref={(ref) => (this._getRef = ref)}
            data={adressList}
            keyExtractor={(item, index) => item.code}
            renderItem={({ item, index }) => (
              <TouchableOpacity key={index} onPress={() => this.handClick(item, index)}>
                <Text
                  style={[
                    styles.adress,
                    index === label[act].index ? styles.active : '',
                  ]}
                >
                  {item.name}
                </Text>
              </TouchableOpacity>
            )}
          />
        </View>
      </Modal>
    );
  }

  checkAderss = () => {
    const { label } = this.state;
    let checkStatus = true;
    label.forEach((v, i) => {
      if (!v.selectName) {
        msg.emit('app:tip', { text: '地址还没有选完整哦' });
        checkStatus = false;
        return checkStatus;
      }
    });
    return checkStatus;
  };

  reset = () => {
    const { label } = this.state;
    label.map((v, i) => {
      label[i].selectName = '';
      label[i].index = '';
      label[i].code = '';

      if (label[i].type == 'province') {
        label[i].name = '省份';
      } else if (label[i].type == 'city') {
        label[i].name = '城市';
      } else if (label[i].type == 'county') {
        label[i].name = '县区';
      }
    });

    this.setState({ label: [...this.state.label], act: 0 }, () => {
      this.getAdressList('');
    });
  }

  submit = () => {
    const { label } = this.state;
    if (this.checkAderss()) {
      let list = [];
      let adressName = '';
      label.forEach((v, i) => {
        list.push({ name: v.selectName, id: v.id, type: v.type });
        adressName += v.selectName;
      });
      let adress = {
        list,
        adressName,
      };

      this.reset();
      this.props.changeVisible();
      this.props.getAdressData(adress);
    }
  };

  handleLabel = (item, act) => {
    this.setState({
      adressList: [],
    });
    let { label } = this.state;

    // console.log(item);
    this.setState({ act });
    if (act != 0 && !label[act - 1].selectName) {
      if (act == 1) {
        msg.emit('app:tip', { text: '请先选择省份' });
      } else if (act == 2) {
        msg.emit('app:tip', { text: '请先选择省份和城市' });
      }

      return;
    }
    let that = this;
    this.getAdressList(item.code).then((res) => {
      setTimeout(() => {
        if (item.index) {
          that._getRef.scrollToIndex({ viewPosition: 0.5, index: item.index });
        }
      }, 1);
    });
  };

  handClick = (item, index) => {
    let { act, label } = this.state;

    label.map((v, i) => {
      if (i > act) {
        label[i].selectName = '';
        label[i].index = '';
        if (i == 1) {
          label[i].name = '省份';
        } else if (i == 2) {
          label[i].name = '县区';
        }
      }
    });

    this.setState({ label: [...this.state.label] });
    let newAct = act;
    if (act >= label.length - 1) {
    } else {
      newAct = act + 1;
      label[act + 1].code = item.code;
    }
    label[act].index = index;
    label[act].selectName = item.name;
    label[act].id = item.code;
    label[act].name = item.name;

    this.setState({ label: [...this.state.label], act: newAct }, () => {
    });
    if (act >= label.length - 1) {
      return;
    }
    let that = this;
    this.getAdressList(item.code).then((res) => {
      setTimeout(() => {
        if (that._getRef) {
          that._getRef.scrollToOffset({ animated: false, offset: 0 });
        }
      }, 1);
    });
  };
}

const styles = StyleSheet.create({
  centeredView: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.3)',
  },
  adressWrap: {
    width: '100%',
    height: '35%',
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    left: 0,
    bottom: 0,
  },
  labelItem: {
    flexDirection: 'row',
    flex: 1,
  },
  label: {
    flexDirection: 'row',
    alignItems: 'center',
    height: px2dp(76),
    borderWidth: px2dp(1),
    borderBottomColor: splitLineColor_lightgray,
  },
  submitText: {
    fontSize: px2dp(32),
    marginRight: px2dp(26),
  },
  adress: {
    padding: px2dp(20),
    color: fontColorBlack,
    fontSize: px2dp(28),
  },
  itemName: {
    padding: px2dp(20),
    marginRight: px2dp(10),
  },
  active: {
    color: fontColorCoffee
  },
  actLable: {
    color: fontColorCoffee,
    borderBottomWidth: px2dp(4),
    borderBottomColor: fontColorCoffee
  }
});
